package com.dgz.system.service.sysuser.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dgz.common.core.constants.HttpConstants;
import com.dgz.common.core.domain.LoginUser;
import com.dgz.common.core.domain.R;
import com.dgz.common.core.domain.vo.LoginUserVo;
import com.dgz.common.core.enums.ResultCode;
import com.dgz.common.core.enums.UserIdentity;
import com.dgz.common.security.exception.ServiceException;
import com.dgz.common.security.service.TokenService;
import com.dgz.system.domain.sysuser.SysUser;
import com.dgz.system.domain.sysuser.dto.SysUserSaveDTO;
import com.dgz.system.mapper.sysuser.SysUserMapper;
import com.dgz.system.service.sysuser.ISysUserService;
import com.dgz.system.utils.BCryptUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: DongGuoZhen
 * @Date: 2024/12/05/10:40
 * @Description:
 */

@Service
@RefreshScope  // 实现配置自动刷新
@Slf4j
public class SysUserServiceImpl implements ISysUserService {

    @Value("${jwt.secret}")
    private String secret;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public R<String> login(String userAccount, String password) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
       // sql: select password from sys_user where user_account = #{userAccount}
       SysUser sysUser = sysUserMapper.selectOne(queryWrapper.select(SysUser:: getPassword,SysUser::getUserId,SysUser::getNickName).eq(SysUser::getUserAccount, userAccount));
       if(sysUser == null) {
           log.error("登录失败，用户不存在");
           return R.fail(ResultCode.FAILED_USER_NOT_EXISTS);
       }
       if(BCryptUtils.matchesPassword(password,sysUser.getPassword())) {
           // 登录成功 生成token 并存储到redis
           log.info("登录成功，生成token");
           return R.ok(tokenService.createToken(sysUser.getUserId(), secret, UserIdentity.ADMIN.getValue(),sysUser.getNickName(),null));
       }
       log.error("登录失败，密码错误");
       return R.fail(ResultCode.FAILED_LOGIN);
    }

    @Override
    public boolean logout(String token) {
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        return tokenService.deleteLoginUser(token, secret);
    }

    @Override
    public R<LoginUserVo> info(String token) {
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        LoginUser loginUser = tokenService.getLoginUser(token, secret);
        if(loginUser == null) {
            return R.fail();
        }
        LoginUserVo loginUserVo = new LoginUserVo();
        loginUserVo.setNickName(loginUser.getNickName());
        return R.ok(loginUserVo);
    }


    @Override
    public int add(SysUserSaveDTO saveDTO) {
        // 把DTO转换成SysUser
        List<SysUser> sysUsers = sysUserMapper.selectList(
                new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserAccount, saveDTO.getUserAccount()));
        if(CollectionUtil.isNotEmpty(sysUsers)) {
            // 自定义异常
            throw new ServiceException(ResultCode.AILED_USER_EXISTS);
        }
        SysUser sysUser = new SysUser();
        sysUser.setUserAccount(saveDTO.getUserAccount());
        sysUser.setPassword(BCryptUtils.encryptPassword(saveDTO.getPassword()));
        return sysUserMapper.insert(sysUser);

    }
}
